local tunmeng = fk.CreateSkill{
  name = "hanqing__tunmeng",
}

Fk:loadTranslationTable{
  ["hanqing__tunmeng"] = "吞盟",
  [":hanqing__tunmeng"] = "准备阶段，你可以令所有横置角色议事，若结果为：红色，重置意见为黑的角色；黑色，你获得黑色的议事牌。",

  ["#hanqing__tunmeng-invoke"] = "吞盟：是否令所有横置角色议事？",
}

local U = require "packages/utility/utility"

tunmeng:addEffect(fk.EventPhaseStart, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(tunmeng.name) and player.phase == Player.Start and
      table.find(player.room.alive_players, function(p)
        return p.chained and not p:isKongcheng()
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if room:askToSkillInvoke(player, {
      skill_name = tunmeng.name,
      prompt = "#hanqing__tunmeng-invoke",
    }) then
      local tos = table.filter(room:getAlivePlayers(), function(p)
        return p.chained and not p:isKongcheng()
      end)
      event:setCostData(self, {tos = tos})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = event:getCostData(self).tos
    local discussion = U.Discussion(player, targets, tunmeng.name)
    if discussion.color == "red" then
      for _, p in ipairs(targets) do
        if p.chained and not p.dead and discussion.results[p].opinion == "black" then
          p:setChainState(false)
        end
      end
    elseif discussion.color == "black" and not player.dead then
      local cards = {}
      for _, p in ipairs(targets) do
        if not p.dead and p ~= player then
          local ids = table.filter(discussion.results[p].toCards, function (id)
            return table.contains(p:getCardIds("h"), id) and Fk:getCardById(id).color == Card.Black
          end)
          if #ids > 0 then
            table.insertTableIfNeed(cards, ids)
          end
        end
      end
      if #cards > 0 then
        room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonPrey, tunmeng.name, nil, true, player)
      end
    end
  end,
})

return tunmeng
